package main

import (
	"bytes"
	"code.google.com/p/go.crypto/ssh"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

var (
	host     = "127.0.0.1"
	port     = "22"
	username = "root"
	password = "tT565535963"
)

type SSH struct {
	client *ssh.Client
}

func GetConn(host, port, username, password string) *SSH {
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.Password(password),
		},
	}
	client, err := ssh.Dial("tcp", host+":"+port, config)
	if err != nil {
		fmt.Println(err.Error())
	}

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.

	return &SSH{client}
}

func (s *SSH) SendMessage(cmd string) (out string) {
	session, err := s.client.NewSession()
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}
	defer session.Close()

	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run(cmd); err != nil {
		fmt.Println(err.Error())
	}
	return b.String()

	// var read []byte
	// s.stdout.Read(read)
	// return string(read)
}

func FileRead(path string) string {
	fi, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	fd, err := ioutil.ReadAll(fi)
	// fmt.Println(string(fd))
	return string(fd)
}

func gValue(i string) string {
	return strings.Split(i, ":")[1]
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("请输入shell文件")
		return
	}

	body := FileRead(os.Args[1])
	body = strings.Replace(body, "\r", "", -1)
	bodys := strings.Split(body, "\n")
	body = strings.Join(bodys[1:], ";")

	info := strings.Split(strings.Trim(bodys[0], " "), ";")

	session := GetConn(gValue(info[0]), gValue(info[1]), gValue(info[2]), gValue(info[3]))

	fmt.Println(session.SendMessage(body))
}
